package com.wanwanbookstore.servlet;

import com.wanwanbookstore.dao.UserDAO;
import com.wanwanbookstore.entity.User;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    private UserDAO userDAO = new UserDAO();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = userDAO.getUserByUsername(username);
        if (user != null && user.getPassword().equals(password)) {
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            // 判断是否为管理员用户
            if ("admin".equals(username) && "wanwanshudian".equals(password)) {
                session.setAttribute("isAdmin", true);
                response.sendRedirect("admin?action=list");
            } else {
                session.setAttribute("isAdmin", false);
                response.sendRedirect("index.jsp");
            }
        } else {
            request.setAttribute("error", "用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 检查是否有注销成功的提示信息
        String message = request.getParameter("message");
        if ("account_deleted".equals(message)) {
            request.setAttribute("successMessage", "账号已成功注销，感谢您的使用");
        }
        // 默认跳转到登录页面
        request.getRequestDispatcher("login.jsp").forward(request, response);
    }
}